package com.ikas.ai.server.module.morningpaper.model.elements;

import com.ikas.ai.consts.TableDictConsts;
import com.ikas.ai.enums.redis.RedisKeyEnum;
import com.ikas.ai.server.module.data.model.BaseMete;
import com.ikas.ai.server.module.data.model.tdengine.RealDataHis;
import com.ikas.ai.server.module.data.tdDao.DataHisTdMapper;
import com.ikas.ai.server.module.morningpaper.exception.MorningPaperException;
import com.ikas.ai.server.module.morningpaper.util.MorningPaperTimeUtil;
import com.ikas.ai.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AbstractElementNeedsTDEngine extends MorningPaperTopElement{

    @Autowired
    protected RedisUtil redisUtil;
    @Autowired
    protected DataHisTdMapper dataHisTdMapper;
    @Autowired
    MorningPaperTimeUtil morningPaperTimeUtil;

    /**
     * 根据meteId获取对应的遥信测点元数据
     *
     * @param meteId
     * @return
     */
    protected BaseMete getBaseMeteYxCache(Long meteId) {
        BaseMete baseMete = redisUtil.getBean(RedisKeyEnum.BASE_METE_ENTITY_YX.key(meteId), BaseMete.class);
        return baseMete;
    }

    /**
     * 根据meteId获取历史数据
     * @param meteId
     * @return
     */
    protected List<RealDataHis> getMeteHis(Long meteId){
        try {
            return dataHisTdMapper.selectByTableNameTimeAsc(TableDictConsts.DATA_HIS_PREFIX_YX + meteId, morningPaperTimeUtil.getPaperStatisticsStartTime(), morningPaperTimeUtil.getPaperStatisticsEndTime());
        } catch (Exception e) {
            log.info(String.format(MorningPaperException.tdEngineTableNotExistOrDateEmpty,meteId));
            return new ArrayList<>();
        }
    }

    /**
     * 获取当前Element的MeteId，如果有的话
     * @param morningPaperTopElement
     * @return
     */
    protected Long getMeteId(MorningPaperTopElement morningPaperTopElement){
        Long meteId = this.getPoMap().get(morningPaperTopElement.getMorningPaperVariableName()).getMeteId();
        if (meteId==null||meteId==0L){
            throw new MorningPaperException(String.format(MorningPaperException.meteIdOrMeteCodeNotExist, morningPaperTopElement.getMorningPaperVariableName()));
        }
        return meteId;
    }
}
